package com.springboot.frame.web.validate;


import javax.validation.*;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.text.SimpleDateFormat;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * 日期格式验证,可以在{@code format}中添加有效的日期格式
 * @author Canaan
 * @date 2019/8/2 11:52
 */
@Documented
@Constraint(validatedBy = { ValidDate.DateValidator.class })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
public @interface ValidDate {

    String message() default "日期格式不正确";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * 有效的日期格式
     */
    String[] format() default {};


    /**
     * Defines several {@link ValidDate} annotations on the same element.
     *
     * @see
     */
    @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
    @Retention(RUNTIME)
    @Documented
    @interface List {
        ValidDate[] value();
    }

    class DateValidator implements ConstraintValidator<ValidDate, String> {

        private String[] formats;

        @Override
        public void initialize(ValidDate constraintAnnotation) {
            formats = constraintAnnotation.format();
        }

        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            if (value == null || "".equals(value.trim())) {
                return true;
            }
            if (formats.length == 0) {
                return true;
            }

            for (String string : formats) {
                try {
                    SimpleDateFormat formatter = new SimpleDateFormat(string);
                    formatter.parse(value);
                } catch (Exception e) {
                    return false;
                }
            }
            return true;
        }

    }
}
